/*!
 * New Launch.
 * Date: 2015/12/29.
 * Copyright© 2014-2015 Vamaker All Rights Reserved.
 */
require([
    'jquery',
    'pageInit',
    'formValidator',
    'formAjax',
    'notification',
    'flowplayer',
    'materialPreview',
    'holder',
    'uploadFiles'
  ], function ($, vamakerPage, formValidator, formAjax, VamOpMsg, Flowplayer, MaterialPreview, holder, UploadFiles) {
    var $dataFrm = $('#data-frm');
  $(function() {
    var $imprMonitorFormCopy = $('.impr-monitor-url-new').detach().removeClass('hidden'),
        $clickMonitorFormCopy = $('.click-monitor-url-new').detach().removeClass('hidden'),
        $visibleMonitorFormCopy = $('.click-visible-url-new').detach().removeClass('hidden'),
        $showMonitorUrl = $dataFrm.find('input[name="show_monitor_url"]'),
        $clickMonitorUrl = $dataFrm.find('input[name="click_monitor_url"]'),
        $visibleMonitorUrl = $dataFrm.find('input[name="visible_urls"]'),
        $duration = $dataFrm.find('input[name="duration[]"]'),
        validateCallback, newMonitorUrl, delMonitorUrl, urlValidateCallback, durationValidateCallback,
        $materialSource = $('#material_source').find('input[name="material_source"]'),
        $localMaterial = $('#local_upload_material'),
        $customUrl = $('#custom_material_url'),
        $materialUrl = $('.custom-url'),
        $submitBtn = $dataFrm.find('button[type="submit"]'),
        $materialFormCopy = $('.new-custom-url').detach().removeClass('hidden'),
        dataFieldRule, options, dataValidator;
      $materialSource.on('change', function(){
        var $me = $(this),
            meVal = $me.val();
        if (meVal === '1') {
          $customUrl.show();
          $localMaterial.hide();
        } else {
          $customUrl.hide();
          $localMaterial.show();
        }
      });
      $('input[name="material_source"]:checked').trigger('change');

      durationValidateCallback = function (evt) {
        var $me = $(this),
        meVal = $me.val(),
        errorBox = $me.data('err'),
        $errorBox = $me.next('.'+errorBox),
        flag = true,
        msg = '';
        if (meVal === '') {
          flag = false;
          msg = VAM.j('Input cannot be empty!');
        } else if (!/^[0-9]*$/.test(meVal)) {
          flag = false;
          msg = VAM.j('Enter can only be integer!');
        } else if(parseInt(meVal,10) < 0) {
          flag = false;
          msg = VAM.j('Enter cannot be less than 0s!');
        } else if (parseInt(meVal,10) > 15){
          flag = false;
          msg = VAM.j('Enter cannot be more than 15s!');
        };
        if (!flag) {
          msg = '<em class="checky-default-failure">' + msg + '</em>';
          $errorBox.html(msg);
        } else {
          $errorBox.html('');
        };
      };

      urlValidateCallback = function (evt) {
        var $me = $(this),
        meVal = $me.val(),
        errorBox = $me.data('err'),
        $errorBox = $me.next('.'+errorBox),
        strRegex = '^((https|http|ftp|rtsp|mms)?://)'
        flag = true,
        re = new RegExp(strRegex),
        msg = '';
        if (meVal === '') {
          flag = false;
          msg = VAM.j('Material url cannot be empty!');
        } else if (!re.test(meVal)){
          flag = false;
          msg = VAM.j('Please input the correct target Url (starting with http:// or https://)');
        };
        if (!flag) {
          msg = '<em class="checky-default-failure">' + msg + '</em>';
          $errorBox.html(msg);
        } else {
          $errorBox.html('');
        };
      };
    $dataFrm.on('blur', 'input[name="duration[]"]', durationValidateCallback);
    $materialUrl.on('blur', urlValidateCallback);
    newMonitorUrl = function($monitorFormNew, $monitorFormCopy){
      var len = $monitorFormNew.length;
      console.log();
      if (len < 5) {
        $monitorFormClone = $monitorFormCopy.clone(true);
        $monitorFormNew.last().after($monitorFormClone);
      }
    };
    delMonitorUrl = function(evt){
      evt.preventDefault();
      var $me = $(this),
          opRole = $me.data('type');
      $me.parents('.'+ opRole).remove();
    };
    validateCallback = function(evt){
      var $me = $(this), 
          meVal = $me.val(), matchResult,
          $errBox = $me.next(),
          msg = VAM.j('Please input the correct monitor Url (starting with http:// or https://)');
          matchResult = /^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+/.test(meVal);
      if ($me.data('role') === 'click_url') {
        msg = VAM.j('Please input the correct monitor Url (starting with http:// or https://)');
      }
      if (meVal !== '' && !matchResult) {
        $errBox.html('<em class="checky-default-failure">' + VAM.j('Please input the correct monitor Url (starting with http:// or https://)') + '</em>');
      } else {
        $errBox.html('');
      }
    };
    $dataFrm.on('click', '.add-monitor-url', function(evt){
      evt.preventDefault();
      var $me = $(this),
          opType = $me.data('type');
      if (opType === 'impr-monitor-url') {
        newMonitorUrl($('.' + opType), $imprMonitorFormCopy);
      } else if (opType === 'click-monitor-url') {
        newMonitorUrl($('.' + opType), $clickMonitorFormCopy);
      } else if (opType === 'click-visible-url') {
        newMonitorUrl($('.' + opType), $visibleMonitorFormCopy);
      }
    });

    $dataFrm.on('click', '.del-operate', delMonitorUrl);
    $dataFrm.on('blur', 'input[name="show_monitor_url[]"]', validateCallback);
    $dataFrm.on('blur', 'input[name="click_monitor_url[]"]', validateCallback);
    //$dataFrm.on('blur', 'input[name="visible_urls[]"]', validateCallback);

    // Add Material Url
    $dataFrm.on('click', '.add-material-url', function(evt){
      evt.preventDefault();
      var $materialFormNew = $('.custom-material-url'),
        len = $materialFormNew.length;
        $('#custom_material_url_err').html('');
      if (len < 4) {
        $materialFormClone = $materialFormCopy.clone(true);
        $materialFormNew.last().after($materialFormClone);
      }
    });

    // Del Material Url
    $dataFrm.on('click', '.del-operate', function(evt){
      evt.preventDefault();
      var $me = $(this);
      $me.parents('.custom-material-url').remove();
    });
  // New Creative Form.
      dataFieldRule = {
        landing_page_url:{
          rule:{
              required:{
                message:VAM.j('Target Url cannot be empty')
              },
              simpleUrl:{
                message:VAM.j('Please input the correct target Url (starting with http:// or https://)')
              }
          },
          messageContainer:'landing_page_url_err'
        },
        audit_target_url:{
          rule:{
              simpleUrl:{
                message:VAM.j('Please input the correct target Url (starting with http:// or https://)')
              }
          },
          messageContainer:'audit_target_url_err'
        }
      };
      options = {
        submitOnSucceed: false,
        onvalidate: function(evt) {
          if (evt.resultList.length <= 0) {
            var $materialSource = $('#material_source').find('input[name="material_source"]:checked'),
              $duration = $dataFrm.find('input[name="duration[]"]'),
              $materialUrl = $dataFrm.find('input[name="custom_url[]"]'),
              materialSourceVal = $materialSource.val(),
              $inpuMonitorErr = $('.monitor-url-error'),
              monitorFlag = 0;
              $inpuMonitorErr.each(function(){
                if (!!$(this).html()) {
                  monitorFlag += 1;
                };
              });
              if (!!monitorFlag) {
                return false;
              };
            if (materialSourceVal === '0') {
              var materialVal = $('#upload_material').val(),
                  materialNum = $('.creative-preview').length;
                $errorBox = $('#upload_material_err'),
                flag = true,
                msg = '';
              if (materialNum < 2 || materialNum > 4) {
                flag = false;
              };
              if (!flag) {
                msg = '<em class="checky-default-failure">' + VAM.j('Upload material at least 2 and up to 4') + '</em>';
                $errorBox.html(msg);
                return false;
              } else {
                $errorBox.html('');
              };
            } else {
                $materialUrl.trigger('blur', urlValidateCallback);
                $duration.trigger('blur', durationValidateCallback);
                var $inputMaterialErr = $('#custom_material_url').find('.custom-url-err'),
                    $inputDurationErr = $('#custom_material_url').find('.duration-error'),
                urlLen = $('input[name="custom_url[]"]').length,
                materialFlag = 0, durationFlag = 0;
                $inputMaterialErr.each(function(){
                  if (!!$(this).html()) {
                    materialFlag += 1;
                  };
                });
                $inputDurationErr.each(function(){
                  if (!!$(this).html()) {
                    durationFlag += 1;
                  };
                });
                if (!!materialFlag || !!durationFlag) {
                  return false;
                };
                if (urlLen < 2) {
                  $('#custom_material_url_err').html('<em class="checky-default-failure">' + VAM.j('Upload material at least 2 and up to 4') + '</em>');
                  return false;
                };
            };
            $dataFrm.ajaxSubmit({
                beforeSubmit: function() {
                  $submitBtn.button('loading');
                },
                success: function (data) {
                  $submitBtn.button('reset');
                if (data.status === 'success') {
                  VamOpMsg.messager(data);
                  if (VAM.getVar('CLOSE_DIALOG_FLAG') === true) {
                    $('.creative-preview-modal', window.parent.document).find('.btn-default').trigger('click');
                  } else {
                    window.location.href = 'creative-list';
                  }
                } else {
                  VamOpMsg.messager(data);
                }
                }
            });
          };
        }
      };
      formValidator.validate($dataFrm, dataFieldRule, options);
      dataValidator = formValidator.dataValidator;
      dataValidator.addRule('effectiveNumber',function(val, opt){
        return !!(val && /^\d+(\.\d{1,2})?$/.test(val));
      });
  });
  // Init Creative Upload.
  $(function () {
    var $uploadMaterial = $('#upload-material'),
      $uploadMaterialModal = $('#upload-material-modal'),
      $uploadMaterialInput = $('#upload_material'),
      $creativePreviewWrap = $('.creative-preview-wrap'),
      $uploadMaterialOperate = $('#upload-confirm-operate'),
      $creativeMaterialDefault = $('#creative_material_default'),
      videoPluginUrl = VAM.getVar('VIDEO_PLUGIN_URL');
    Flowplayer.conf = {
      swf: videoPluginUrl,
      muted: true,
      preload: 'metadata',
      tooltip: false,
      volume: 0.3
    };
    $uploadMaterialModal.on('hidden.bs.modal', function (evt) {
      var $me = $(this);
      $('#progress .progress-bar').css('width','0%').text('0%');
      $('#files').find('tbody').html('');
    });

    $uploadMaterial.on('click', function (evt) {
      var $me = $(this);
      $uploadMaterialModal.modal('show');
    });
    
    $uploadMaterialOperate.on('click', function(evt) {
      var $me = $(this),
        $uploadMaterialErr = $('#upload_material_err');
        materialId = $me.data('materialId'),
        prevewInfo = $me.data('materialInfo');
      evt.preventDefault();
      // console.log(materialId);
      // console.log(prevewInfo);
      if (materialId !== '') {
        $uploadMaterialInput.val(materialId);
        $uploadMaterialModal.modal('hide');
        $uploadMaterialErr.html('');
        // TODO: creative material preview.
        MaterialPreview.previewMultiple($('.creative-preview-wrap'), prevewInfo, materialId);
        $('.creative-preview-wrap').find('.flowplayer').last().flowplayer();
        $('#creative-preview-details').children().remove();
      } else {
        $uploadMaterialInput.val('');
      };
    });
    $creativePreviewWrap.on('click', '.preview-close', function(evt) {
      var $me = $(this),
        $parent = $me.parent();
      evt.preventDefault();

      $parent.fadeOut(function() {
        $parent.remove();
        if ($creativePreviewWrap.find('.creative-preview').length === 0) {
          if ($creativeMaterialDefault.hasClass('hidden')) {
            $creativeMaterialDefault.removeClass('hidden');
          } else {
            $creativeMaterialDefault.show();
          };
          $("#upload_material").val("");
        };
      });
    });
  });

  // Upload Creative Material.
  $(function () {
    'use strict';
    var url = VAM.getVar('UPLOAD_MATERIAL_URL'),
        $fileUpload = $('#fileupload'),
        $progressBar = $('#progress .progress-bar'),
        $table = $('#files').find('table tbody');
    $fileUpload.fileupload({
        url: url,
        dataType: 'json',
        done: function (e, data) {
          if (data.result.status === 'success') {
            var materialData = data.result.data,
             list = materialData['table'],
             listStr = '';
            // console.log(materialData);
            VamOpMsg.messager(data.result);
            listStr = '<tr>'
                    + '<td>' + materialData.id + '</td>'
                    + '<td>' + list.name + '</td>'
                    + '<td>' + list.size + '</td>'
                    + '<td>' + list.date + '</td>'
                    + '<td>' + list.judgeInfo + '</td>'
                    + '<td>' + list.updater + '</td>'
                    + '</tr>';
            $table.append(listStr);
            $('#upload-confirm-operate').data('materialId', materialData.id).data('materialInfo', materialData['preview']);
          }else {
            VamOpMsg.messager(data.result);
            $('#upload-confirm-operate').data('materialId', '');
          };
        },
        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $progressBar.css('width','0%').text('0%');
            $progressBar.css(
                'width',
                progress + '%'
            ).text(progress + '%');
        }
    })
    .prop('disabled', !$.support.fileInput)
    .parent().addClass($.support.fileInput ? undefined : 'disabled');
  });

  // Video Creative Preview.
  $(function() {
    var videoPluginUrl = VAM.getVar('VIDEO_PLUGIN_URL'),
      $creativePreviewWrap = $('.creative-preview-details'),
      width = $('.creative-width').val(),
      height = $('.creative-height').val(),   
      type = $('.creative-type').val(),
      url = $('.creative-url').val(),
      info = {}, materialId = '';
    Flowplayer.conf = {
      swf: videoPluginUrl,
      engine: 'flash',
      muted: true,
      preload: 'auto',
      tooltip: false,
      volume: 0.3
    };
    info = {
      'width': width,
      'height': height,
      'type': type,
      'address': url
    };
    // console.log(info);
    // MaterialPreview.previewMultiple($('.creative-preview-wrap'), info, materialId);
    // $('.creative-preview-wrap').find('.flowplayer').flowplayer();
    $('.creative-preview-wrap').find('.flowplayer').each(function(){
      $(this).flowplayer();
    })
  });
});
